package com.seahorse.youliao.controller;

import com.seahorse.youliao.aop.NoRepeatSubmit;
import com.seahorse.youliao.common.ResponseEntity;
import com.seahorse.youliao.exception.BusinessException;
import com.seahorse.youliao.service.SysMenuService;
import com.seahorse.youliao.service.SysRoleService;
import com.seahorse.youliao.service.SysUserService;
import com.seahorse.youliao.service.entity.SysMenuDTO;
import com.seahorse.youliao.service.entity.SysRoleDTO;
import com.seahorse.youliao.service.entity.SysUserDTO;
import com.seahorse.youliao.util.SecurityUtils;
import com.seahorse.youliao.utils.BeanUtil;
import com.seahorse.youliao.utils.MD5;
import com.seahorse.youliao.vo.request.UserRegisterVO;
import com.seahorse.youliao.vo.response.SysRoleResponseVO;
import com.seahorse.youliao.vo.response.SysUserInfoResponseVo;
import com.seahorse.youliao.vo.response.SysUserMenuResponseVO;
import com.wf.captcha.ArithmeticCaptcha;
import com.zengtengpeng.operation.RedissonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @ProjectName: youliao
 * @Package: com.seahorse.youliao.controller
 * @ClassName: LoginController
 * @Description: 用户登录
 * @author:songqiang
 * @Date:2020-01-10 10:58
 **/
@Api(value = "LoginController", tags = "系统-注册、验证码、登录菜单加载")
@RequestMapping("/auth")
@RestController
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Resource
    private RedissonObject redissonObject;



    /**
     * 用户注册成功可以使用账号登录 或则 短信验证码登录
     * 注册的账户会初始化部分菜单权限
     * 目前两种登录认证已接入
     * @return
     */
    @NoRepeatSubmit
    @ApiOperation("用户注册")
    @PostMapping(value = "/user/register")
    public void userRegister(@RequestBody UserRegisterVO registerVO){


        // 根据手机号查询 验证码判断
        String redisCode = redissonObject.getValue(registerVO.getMobile());
        if(StringUtils.isBlank(redisCode) || !registerVO.getCode().equals(redisCode)){
            logger.info("验证码已过期 registerVO = {}",registerVO);
            throw new BusinessException("验证码已过期");
        }

        // 清除验证码
        redissonObject.delete(registerVO.getMobile());

        // 注册
        SysUserDTO userDTO = new SysUserDTO();
        userDTO.setPhone(registerVO.getMobile());
        userDTO.setPassword(MD5.md5(registerVO.getPassword()));
        userDTO.setEmail(registerVO.getEmail());

        sysUserService.register(userDTO);

    }



    /**
     * 短信登录发送验证码
     * @return
     */
    @NoRepeatSubmit
    @ApiOperation("发送短信验证码")
    @GetMapping(value = "/mobile/code")
    public ResponseEntity<Object> sendMobileCode(@RequestParam(value = "mobile") String mobile){


        //生成随机6位数字验证码
        String captcha = String.valueOf((int)((Math.random()*9+1)*100000));

        //发送短信验证码到指定手机号


        // 保存到redis 5分钟
        redissonObject.setValue(mobile,captcha,60*5*1000L);
        return ResponseEntity.ok("成功",captcha);
    }


    /**
     * 账号登录图片验证码
     * @return
     */
    @NoRepeatSubmit
    @ApiOperation("获取验证码")
    @GetMapping(value = "/captcha")
    public ResponseEntity<Object> getCode(){
        // 算术类型 https://gitee.com/whvse/EasyCaptcha
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = captcha.text();
        String uuid = UUID.randomUUID().toString().replace("-","");
        // 保存到redis
        redissonObject.setValue(uuid,result,60*5*1000L);
        // 验证码信息
        Map<String,Object> imgResult = new HashMap<String,Object>(2){{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return ResponseEntity.ok("成功",imgResult);
    }

    /**
     * 登录用户信息
     * @return
     */
    @ApiOperation("登录用户信息")
    @GetMapping(value = "/user/info")
    public SysUserInfoResponseVo getUserInfo(){

        //查询用户信息
        SysUserDTO userDTO = new SysUserDTO();
        userDTO.setUserName(SecurityUtils.getUsername());
        SysUserDTO user = sysUserService.get(userDTO);
        SysUserInfoResponseVo responseVo = BeanUtil.convert(user,SysUserInfoResponseVo.class);

        //查询角色信息
        List<SysRoleDTO> roles = sysRoleService.getRolesByUserId(user.getId());
        List<SysRoleResponseVO> roleList = BeanUtil.convert(roles,SysRoleResponseVO.class);
        responseVo.setRoles(roleList);

        //查询角色权限信息
        List<String> permissions = sysMenuService.getPermissionsByUserId(user.getId());
        responseVo.setPermissions(permissions);

        return responseVo;
    }

    /**
     * 登录查询用户菜单
     * @return
     */
    @ApiOperation("登录查询用户菜单")
    @GetMapping(value = "/user/nav")
    public List<SysUserMenuResponseVO> getUserNav(){

        List<SysMenuDTO> list = sysUserService.getUserNav(SecurityUtils.getUsername());
        //处理数据
        return BeanUtil.convert(list,SysUserMenuResponseVO.class);
    }

}
